import React, { useState,useEffect } from 'react'
import './style.less';
import logo from '@/assets/img/logo.jpeg'
import {Tooltip,Button,notification,Card,Carousel,Progress,Table,Modal, Empty,ConfigProvider} from 'antd';
import taskListData from './data';
import axios from 'axios'
import watermark from 'watermark-package'
type todayAnalyseDataType= {
  messageCount?:number;
  inHandProcess?:ProcessType;
  delayProcess?:ProcessType;
}
type ProcessType = {
  num:number|string,
  process:number|string
}
const Census = () => {
  // 今日任务分块
  const SPLITNUMS = 5
  // 延期任务、进行中任务、邮件数量
  const [todayAnalyseData,setTodayAnalyse] = useState<todayAnalyseDataType>({
    messageCount:100,//邮件数执行中任务
    inHandProcess:{
      num:5000,
      process:'20%'
    },
    
    delayProcess:{
      num:3000,// 延期任务
      process:'50%'
    }
    })
  // 外出人员List
  const [personnelList,setPersonnelList] = useState<Array<{name:string,id?:string|number}>>(
    [
      {name:'张三1',id:1},
      {name:'张三2',id:1},
      {name:'张三3',id:1},
      {name:'张三4',id:1},
      {name:'张三5',id:1},
      {name:'张三6',id:1},
      {name:'张三7',id:1},
      {name:'张三8',id:1},
      {name:'张三9',id:1},
      {name:'张三10',id:1},
      {name:'张三11',id:1},
      {name:'张三12',id:1},
      {name:'张三13',id:1},
      {name:'张三14',id:1},
      {name:'张三15',id:1},
      {name:'张三16',id:1},
      {name:'张三17',id:1},
      {name:'张三18',id:1},
    ]
  );
  // 培训List
  const [trainList,setTrainList] = useState<Array<{name:string,trainingDuration:string,id:string|number}>>(
    [
      {name:'张三1',trainingDuration:'1.5小时',id:1},
      {name:'张三2',id:1,trainingDuration:'1.5小时'},
      {name:'张三4',id:1,trainingDuration:'2.5小时'},
      {name:'张三3',id:1,trainingDuration:'3.5小时'},
      {name:'张三5',id:1,trainingDuration:'4.5小时'},
      {name:'张三6',id:1,trainingDuration:'5.5小时'},
      {name:'张三7',id:1,trainingDuration:'6.5小时'},
      {name:'张三8',id:1,trainingDuration:'7.5小时'},
      {name:'张三9',id:1,trainingDuration:'8.5小时'},
      {name:'张三10',id:1,trainingDuration:'9.5小时'},
      {name:'张三11',id:1,trainingDuration:'10.5小时'},
      {name:'张三12',id:1,trainingDuration:'11.5小时'},
      {name:'张三13',id:1,trainingDuration:'12.5小时'},
      {name:'张三14',id:1,trainingDuration:'13.5小时'},
      {name:'张三15',id:1,trainingDuration:'14.5小时'},
      {name:'张三16',id:1,trainingDuration:'15.5小时'},
      {name:'张三17',id:1,trainingDuration:'16.5小时'},
      {name:'张三18',id:1,trainingDuration:'17.5小时'},
    ]
  );
  // 任务列表
  const [greenRankList,setGreenRankList] = useState<Array<{name:string,num:number,process:number,id?:string|number}>>([
    {name:'张三',num:10,process:100},
    {name:'李四',num:4,process:20},
    {name:'张三',num:10,process:30},
    {name:'张三',num:10,process:30},
    {name:'李四',num:4,process:20},
    {name:'张三',num:10,process:30},
  ]);
  const [isModalVisible,setIsModalVisible] = useState<boolean>(false);
  const [content,setContent] = useState<string>('');
  // 今日任务
  const [taskList,setTaskList] = useState(taskListData)
  const [currentIndex,setCurrentIndex] = useState(0);
  const columns = [
  {
    title: '序号',
    width:60,
    dataIndex: 'index',
    key: 'index',
    render:(text:string, record:any, index:number)=> (
      <div>{index+1}</div>
    )
  },
  {
    title: '工作内容',
    dataIndex: 'workContent',
    key: 'workContent',
    render:(text:string, record:any, index:number)=> (
      record.workContent.length>40?
      <Tooltip title={record.workContent}>
        <div className='task-content-style'>{record.workContent}</div>
      </Tooltip>
      :<div className='task-content-style'>{record.workContent}</div>
    ),
    width:300
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render:(text:string, record:any, index:number)=> {
      if(record.status==='1'){
        return (<Button type="link" size='small'>进行中</Button>)
      }else if(record.status==='2'){
        return (<Button type="link" size='small' style={{color: '#52c41a'}}>已完成</Button>)
      }else if(record.status==='3'){
        return (<Button type="link" size='small' className='custom-btn'><span>延期中</span></Button>)
      }

    }
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
  },
  {
    title: '区域',
    dataIndex: 'area',
    key: 'area',
  },
  {
    title: '比例',
    dataIndex: 'process',
    key: 'process',
    render:(text:number, record:any, index:number)=>(
      <div style={{color:record?.isPass === 0 ?'#dc6068':'#53b095'}}>{text}%</div>
    )
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    render:(text:string, record:any, index:number)=> (
      record.remark.length>40?
      <Tooltip  title={record.remark}>
        <div className='task-content-style'>{record.remark}</div>
      </Tooltip>
      :<div className='task-content-style'>{record.remark}</div>
    ),
    width:300
  },
  

  ];
  const handleArrayData = (list:any[],step:number)=> {
    const result = [];
    for(var i=0,len=list.length;i<len;i+=step){
      result.push(list.slice(i,i+step));
    }
    return result;
  }
  const getKeyframes = (keyframesName:any)=>{//通过定义的动画函数名来查询函数
    let styleSheet:any = document.styleSheets;//获取所有样式表
    let animation:any={};//定义一个animation来装获得的值
    styleSheet = Array.from(styleSheet).filter((v:any)=> !v.href)

    for (let i = 0; i < styleSheet.length; i++) {//遍历循环获取styleSheet
        if(styleSheet[i].cssRules){
          for (let j = 0; j < styleSheet[i].cssRules.length; j++) {//遍历循环获取styleSheet[i].cssRules
              //判断样式名字是否为CSSKeyframesRule
              if (styleSheet[i].cssRules[j].constructor.name === 'CSSKeyframesRule'){
                  //再判断此时这个动画函数名是否为传入的值
                  if (keyframesName === styleSheet[i].cssRules[j].name){
                      //获取此时的cssRules，index，和styleSheet
                      animation.cssRules = styleSheet[i].cssRules[j];
                      animation.index = j;
                      animation.styleSheet = styleSheet[i]
                      return animation//返回获取的animation
                  }
              }
          }
        }
    }
  }
  const setterKeyframes =(list:any[])=>{
    const deepClone = [...list];
    const topArr:any[] = [];
    deepClone.forEach(it=> {
      if(it.list && it.list.length>0){
        const total = (it.list.length * 83) - (SPLITNUMS *83);
        let animation_duration = it.list.length>15?'30s':'10s';
        topArr.push({total,animation_duration})
      }
    })
    let styleKeyFram = ''
    topArr.forEach((it,i)=> {
      let index = i+1;
      styleKeyFram+='@keyframes scoll'+index+'{\n' +
      '            0%{\n' +
      '                top: 0px;\n' +
      '            }\n' +
      '            100%{\n' +
      '                top: -'+it.total+'px;\n' +
      '                 display:none;\n'+
      '            }\n' +
      '        }\n'+
      '.donghua'+index+'{\n'+
        'animation: scoll'+index+' linear '+it.animation_duration+' infinite;\n'+
        '-webkit-animation: scoll'+index+' linear '+it.animation_duration+' infinite;\n'+
        'position: relative;\n'+
      '}\n'
    })
    // 创建style标签
    const style = document.createElement('style');
    // 设置style属性
    style.type = 'text/css';
    // 将 keyframes样式写入style内
    style.innerHTML = styleKeyFram;
    // 将style样式存放到box标签
    document.head.appendChild(style);
  }
  const getInit =()=> {
    axios({
      method:'get',
      url:'/system/work/getTodayAnalyse'
    }).then(res=> {
      console.log(res.data);
      setTodayAnalyse(res.data)
    })
    axios({
      method:'get',
      url:'/system/work/getTopAnalyse'
    }).then(res=> {
      // console.log(res.data);
      setGreenRankList(res.data)
    })
    axios({
      method:'get',
      url:'/system/work/getLeaveUserList'
    }).then(res=> {
      // console.log(res.data);
      setPersonnelList(res.data);
    })
    axios({
      method:'get',
      url:'/system/work/getLeaveUserList'
    }).then(res=> {
      // console.log(res.data);
      setPersonnelList(res.data);
    })
    axios({
      method:'get',
      url:'/system/work/getTrainUserList'
    }).then(res=> {
      // console.log(res.data);
      setTrainList(res.data)
    })
    axios({
      method:'get',
      url:'/system/work/getNotice'
    }).then(res=> {
      if(res.data?.isShow === '1'){
        setIsModalVisible(true);
        setContent(res.data?.content);
        setTimeout(()=> {
          setIsModalVisible(false);
        },5000)
      }
    })
  }
  // 获取进入任务大列表
  const getWorkListData = ()=> {
    axios.get('/system/work/getAllWorkList')
    .then(res=> {
      if(res.data){
        setTaskList(res.data);
        setterKeyframes(res.data);
        let id = setInterval(() => {
          const maxLength = res.data.length;
          setCurrentIndex(index => index < maxLength-1 ? index + 1 : 0);
        }, 10000);
        return ()=> {
          clearInterval(id);
        }
      }
    })
  }
  const getWaterPrint = (str:string)=> {
    watermark.setWaterMark(
      {
         w_texts: ['SRANSIT', '创源']
      }
   )
  }
  useEffect(()=> {
    getInit();
    getWorkListData();
    // setterKeyframes(taskList)
    // let id = setInterval(() => {
    //   const maxLength = taskList.length;
    //   setCurrentIndex(index => index < maxLength-1 ? index + 1 : 0);
    // }, 10000);
    // 轮询固定接口
    // let polling = setInterval(()=> {
    //   getInit();
    // },60000)
    getWaterPrint('创源');
    return () =>{
      // clearInterval(id);
      // clearInterval(polling);
    }
  },[]);
  return (
    <div className="Census">
      {/* <div className="header">
        <div className='flex-box'>
          <img className='logo' src={logo} alt="logo" />
          <div className="show-date">{date}</div>
        </div>
        <div className='right-content'>
          <div style={{marginRight:80}}>
            <Tooltip placement="right" color={'#1890ff'} visible={true} title='2000'>
              <i className='iconfont icon-yanchi fz20'></i>
            </Tooltip>
          </div>
          <div style={{marginRight:80}}>
            <Tooltip placement="right" color={'#1890ff'} visible={true} title='2000'>
              <i className='iconfont icon-zhihangzhong fz20'></i>
            </Tooltip>
          </div>
          <div className='relative' style={{marginRight: 10}}>
            <i className='iconfont icon-xinfeng fz16'></i>
            <span>1</span>
          </div>
          <div className='relative notice'>
            <i onClick={()=> {
              notification.open({
                bottom: 200,
                message: '消息通知',
                description:
                  '您有一条新消息,请及时查收!',
                duprocessn: 0,
              })
              
            }} className='iconfont icon-xiaoxi fz16'></i>
            <span></span>
          </div>
        </div>
      </div> */}
      <div className='personnel'>
        <div style={{flex:1}}>
          <Card size='small' title="外出人员" style={{height:150,overflow:'hidden' }}>
            <Carousel autoplay dotPosition="right" autoplaySpeed={5000}>
              {
                handleArrayData(personnelList,4).map((it:any,i:number)=>(
                  <div className='wrap-scroll' key={`key${i}`}>
                  {
                    it.map((itChild:any,indexChild:number)=> (
                      <p key={indexChild}>{itChild.name}</p>
                    ))
                  }
                </div>
                ))
              }
            </Carousel>
          </Card>
          <Card size='small' title="延期" extra={<span className='del'>延</span>} style={{height:100,overflow:'hidden',marginTop:8 }}>
            <div className='del-num'>{todayAnalyseData?.delayProcess?.num}</div>
            <div className='flex-end'>{todayAnalyseData?.delayProcess?.process}%</div>
          </Card>
        </div>
        <div style={{flex:1}}>
          <Card size='small' title="培训" style={{marginLeft:20,height:150,overflow:'hidden' }}>
            <Carousel autoplay dotPosition="right" autoplaySpeed={5000}>
              {
                handleArrayData(trainList,4).map((it:any,i:number)=> (
                  <div className='flex-box-wrap' key={i}>
                    {
                      it.map((itChild:any,indexChild:number)=> (
                        <div key={indexChild} className='flex-box-between'>
                          <span>{itChild.name}</span><span>{itChild.trainingDuration}小时</span>
                        </div>
                      ))
                    }
                  </div>
                ))
              }
            </Carousel>
          </Card>
          <Card size='small' title="执行中" extra={<span className='del zhixing'>执</span>} style={{height:100,overflow:'hidden',marginTop:8,marginLeft:20 }}>
            <div className='del-num'>{todayAnalyseData?.inHandProcess?.num}</div>
            <div className='flex-end zhixing'>{todayAnalyseData?.inHandProcess?.process}%</div>
          </Card>
        </div>
        <Card size='small' title="绿榜" style={{ width: 400,marginLeft:20,height:258,flex:1 }}>
          <Carousel autoplay dotPosition="right" autoplaySpeed={5000}>
            {
              handleArrayData(greenRankList,4).map((it:any,i:number)=> (
                <div className='flex-box-lvbang' key={i}>
                  {
                    it.map((itChild:any,indexChild:number)=> (
                      <div className='lvbang-items' key={indexChild}>
                        {/* <div className='lvbang-name'>{itChild.name}</div> */}
                        <div className='task-number'>
                          <div className='task-text'>
                            <div className='task-text-name'>{itChild.name}</div>
                            <div>今日任务数{itChild.num}</div>
                            {/* <div>总任务进度{itChild.speed}%</div> */}
                          </div>
                          <Progress size="small" percent={itChild.process} />
                        </div>
                      </div>
                    ))
                  }
                </div>
              ))
            }
          </Carousel>
        </Card>
      </div>
      <div className="task-content">
        <Card size='small' title="今日任务">
          <div className='task-wrap'>
          {/* <Carousel autoplay dotPosition="right" autoplaySpeed={10000}> */}
            <div className='task-wrap-overflow'>
              {/* {
                handleArrayData(taskList,1).map((itTask,indexTask)=>(
                  <div key={indexTask}>
                    {
                      itTask.map((item,index)=> (
                        <Card style={{marginBottom:12}} key={index} size='small' type="inner" title={<div style={{fontSize:16,fontWeight:'bold'}}>{item.name}</div>}>
                          <Table rowKey={'id'} pagination={false} size="small" dataSource={item.list||[]} columns={columns} />
                        </Card>
                      ))
                    }
                  </div>
                ))
              }  */}
              {/* {
                taskList.map((item,index)=> (
                  <Card style={{marginBottom:12}} key={index} size='small' type="inner" title={item.name}>
                    <Table rowKey={'id'} pagination={false} size="small" dataSource={item.list||[]} columns={columns} />
                  </Card>
                ))
              } */}

              {/* {
                handleArrayData(taskList,1).map((itTask,indexTask)=>(
                   <div className='task-wrap' key={indexTask}>
                     <div className='task-wrap-overflow' >
                      <div key={indexTask}>
                        {
                          itTask.map((item,index)=> (
                            <Card style={{marginBottom:12}} key={index} size='small' type="inner" title={<div style={{fontSize:16,fontWeight:'bold'}}>{item.name}</div>}>
                              <div className='wrap-scroll-box'>
                                <div className='table-scroll donghua'>
                                  <Table className='' rowKey={'id'} pagination={false} size="small" dataSource={item.list||[]} columns={columns} />
                                </div>
                              </div>
                            </Card>
                          ))
                        }
                      </div>
                     </div>
                  </div>
                ))
              } */}


              
                <Card style={{marginBottom:12}} size='small' type="inner" title={<div style={{fontSize:18,fontWeight:'bold',textAlign:'center'}}>{taskList[currentIndex]?.name ||''}</div>}>
                  <div className='wrap-scroll-box'>
                    {/* donghua active */}
                    <div className={currentIndex+1 ? `table-scroll donghua${currentIndex+1}`:'table-scroll'}>
                      <ConfigProvider renderEmpty={()=> (
                        <Empty
                          imageStyle={{
                              marginTop:100,
                              height: 60,
                          }}
                          description={
                            <span>暂无数据</span>
                          }
                        >
                        </Empty>
                      )}>
                        <Table rowKey={'id'} pagination={false} size="small" dataSource={taskList[currentIndex]?.list||[]} columns={columns} />
                      </ConfigProvider>
                    </div>
                  </div>

                </Card>
              
            </div>
          {/* </Carousel> */}
          </div>
          
        </Card>
        
      </div>
      <div hidden={!todayAnalyseData?.messageCount} className='fixed-box'>
        <i className='iconfont icon-xinfengtianchong fz16'></i>
        <span>{todayAnalyseData?.messageCount}</span>
      </div>
      <Modal okText={'确定'} cancelText={'取消'} title={<div><i style={{marginRight:5,color:'#5ec2c6'}} className='iconfont icon-lingdang'></i>消息通知</div>} visible={isModalVisible} onOk={()=> setIsModalVisible(false)} onCancel={()=>setIsModalVisible(false)}>
        <div dangerouslySetInnerHTML={{__html:content}} />
      </Modal>
    </div>
  )
}

export default Census
